from flask import Blueprint, request, jsonify, send_file
from database import UploadDAO
from file_manager import FileManager
from math import ceil
from utils.logger import get_logger
import os

logger = get_logger(__name__)


def create_library_routes(upload_dao: UploadDAO, file_manager: FileManager):
    """创建库管理相关路由"""

    library_bp = Blueprint('library', __name__)

    @library_bp.route('/library', methods=['GET'])
    def get_library_files():
        """获取库文件列表"""
        try:
            file_type = request.args.get('type', 'all')
            page = int(request.args.get('page', 1))
            page_size = int(request.args.get('pageSize', 12))
            search = request.args.get('search', '')
            sort_by = request.args.get('sortBy', 'time_desc')
            filter_type = request.args.get('filterType', 'all')

            result = upload_dao.get_uploads(
                file_type=file_type,
                page=page,
                page_size=page_size,
                search=search,
                sort_by=sort_by,
                filter_type=filter_type
            )

            items = []
            for file in result['files']:
                items.append({
                    'file_id': file['file_id'],
                    'original_name': file['original_name'],
                    'file_type': file['file_type'],
                    'file_size': file['file_size'],
                    'upload_time': file['upload_time']
                })

            return jsonify({
                'success': True,
                'items': items,
                'total': result['total'],
                'page': result['page'],
                'pageSize': result['page_size'],
                'totalPages': ceil(result['total'] / result['page_size'])
            })

        except Exception as e:
            logger.error(f"获取库文件失败: {e}")
            return jsonify({'success': False, 'message': '获取文件列表失败'}), 500

    @library_bp.route('/library/<file_id>', methods=['DELETE'])
    def delete_library_file(file_id):
        """删除库文件"""
        try:
            success = upload_dao.delete_upload(file_id)

            if success:
                return jsonify({'success': True, 'message': '删除成功'})
            else:
                return jsonify({'success': False, 'message': '删除失败'}), 500

        except Exception as e:
            logger.error(f"删除文件失败: {e}")
            return jsonify({'success': False, 'message': '删除失败'}), 500

    @library_bp.route('/library/batch-delete', methods=['POST'])
    def batch_delete_library_files():
        """批量删除库文件"""
        try:
            data = request.get_json()
            file_ids = data.get('fileIds', [])

            if not file_ids:
                return jsonify({'success': False, 'message': '没有选择文件'}), 400

            success = upload_dao.batch_delete_uploads(file_ids)

            if success:
                return jsonify({'success': True, 'message': f'成功删除 {len(file_ids)} 个文件'})
            else:
                return jsonify({'success': False, 'message': '批量删除失败'}), 500

        except Exception as e:
            logger.error(f"批量删除失败: {e}")
            return jsonify({'success': False, 'message': '批量删除失败'}), 500

    @library_bp.route('/preview-file/<file_id>')
    def preview_file(file_id):
        """获取文件预览"""
        try:
            upload = upload_dao.get_upload_by_id(file_id)

            if not upload:
                return jsonify({'error': '文件不存在'}), 404

            if upload['preview_path'] and os.path.exists(upload['preview_path']):
                return send_file(upload['preview_path'])
            elif os.path.exists(upload['file_path']):
                return send_file(upload['file_path'])
            else:
                return jsonify({'error': '预览文件不存在'}), 404

        except Exception as e:
            logger.error(f"获取预览失败: {e}")
            return jsonify({'error': '获取预览失败'}), 500

    @library_bp.route('/preview-video/<file_id>')
    def preview_video(file_id):
        """获取文件预览"""
        try:
            upload = upload_dao.get_upload_by_id(file_id)

            if not upload:
                return jsonify({'error': '文件不存在'}), 404

            file_type = upload['original_name'].lower() if upload['original_name'] else ''
            file_path = upload['file_path']
            preview_path = upload['preview_path']

            if file_type.endswith('.mp4'):
                # 如果是视频文件，返回原始视频路径
                if file_path and os.path.exists(file_path):
                    return send_file(file_path)
                else:
                    return jsonify({'error': '视频文件不存在'}), 404
            else:
                # 否则返回预览图
                if preview_path and os.path.exists(preview_path):
                    return send_file(preview_path)
                else:
                    return jsonify({'error': '预览文件不存在'}), 404

        except Exception as e:
            logger.error(f"获取预览失败: {e}")
            return jsonify({'error': '获取预览失败'}), 500

    return library_bp


